<template>
  <a-modal
    v-model:visible="visible"
    title="提示"
    :confirm-loading="confirmLoading"
    cancelText="取消"
    okText="确定"
    @ok="handleOk"
  >
    <p>{{ modalText }}</p>
  </a-modal>
  <a-spin :spinning="spinning">
    <div class="mainClass">

      <a-card class="topClass" hoverable:true>
      <span>
       距离考试结束还有：
         <exam-timer v-model="paperData.leftSeconds" :value="paperData.leftSeconds" v-if="flag" @timeout="doHandler()"/>
      </span>

        <a-button type="primary"  style="float: right" @click="handHandExam()">
          <template #icon><check-outlined /></template>
          {{ handleText }}
        </a-button>
      </a-card>

      <a-card class="leftClass">
        <div class="answerSheet">
          <div class="answerSheetText">答题卡</div>
          <a-tag color="default" style=" margin-top: 2%; margin-bottom: 2%">未作答</a-tag>
          <a-tag color="success" style=" margin-top: 2%; margin-bottom: 2%">已做答</a-tag>
          <a-tag color="warning" style=" margin-top: 2%; margin-bottom: 2%">正在做</a-tag>
        </div>
        <div class="single" v-if="paperData.radioList!==undefined && paperData.radioList.length > 0">
          <div class="answerSheetText">单选题</div>
          <a-tag v-for="item in paperData.radioList" :key="item" :color="cardItemClass(item.answered, item.quId)"
                 style=" margin-top: 2%; margin-bottom: 2%" @click="handSave(item)">{{ item.sort + 1 }}
          </a-tag>
        </div>
        <div class="multiple" v-if="paperData.multiList!==undefined && paperData.multiList.length > 0">
          <div class="answerSheetText">多选题</div>
          <a-tag v-for="item in paperData.multiList" :key="item" :color="cardItemClass(item.answered, item.quId)"
                 style=" margin-top: 2%; margin-bottom: 2%" @click="handSave(item)">{{ item.sort + 1 }}
          </a-tag>
        </div>
        <div class="judge" v-if="paperData.judgeList!==undefined && paperData.judgeList.length > 0">
          <div class="answerSheetText">判断题</div>
          <a-tag v-for="item in paperData.judgeList" :key="item" :color="cardItemClass(item.answered, item.quId)"
                 style=" margin-top: 2%; margin-bottom: 2%" @click="handSave(item)">{{ item.sort + 1 }}
          </a-tag>
        </div>
      </a-card>

      <a-card class="reightClass">
        <p v-if="quData.content">{{ quData.sort + 1 }}.{{ quData.content }}</p>
        <p v-if="quData.image!=null && quData.image!=''">
          <a-image :src="quData.image" :width="100" fallback=""
                   style="max-width:100%;"/>
        </p>
        <div v-if="quData.quType === 1 || quData.quType===3">
          <a-radio-group v-model:value="radioValue"  size="large">
            <a-radio style="  display:flex; margin-top: 10%" v-for="item in quData.answerList" :key="item"
                     :value="item.id">
              {{ item.abc }}.{{ item.content }}
              <div v-if="item.image!=null && item.image!=''" style="clear: both">
                <a-image :src="item.image" :width="100" fallback=""
                         style="max-width:100%;"/>
              </div>
            </a-radio>
          </a-radio-group>
        </div>
        <div v-if="quData.quType === 2">
          <a-checkbox-group v-model:value="multiValue" >
            <a-checkbox v-for="item in quData.answerList" :key="item" :value="item.id">{{ item.abc }}.{{ item.content }}
              <div v-if="item.image!=null && item.image!=''" style="clear: both">
                <a-image :src="item.image" :width="100" fallback=""
                         style="max-width:100%;"/>
              </div>
            </a-checkbox>
          </a-checkbox-group>
        </div>
        <a-button v-if="showPrevious" type="primary" @click="handPrevious()" style="margin-top: 1%;">
          上一题
        </a-button>
        <a-button v-if="showNext" type="warning" @click="handNext()" style="margin-top: 1%; margin-left: 2%">
          下一题
        </a-button>
      </a-card>
    </div>
  </a-spin>
</template>
<script>

import {fillAnswer, handExam, paperDetail, quDetail} from "@/api/module/exam";
import {reactive, ref} from 'vue';
import {useRoute} from 'vue-router';
import ExamTimer from '@/view/component/ExamTimer'
import {message} from "ant-design-vue";
import router from "@/route";
export default {
  components: {ExamTimer},
  setup() {
    // 交卷对话框
    const modalText = ref('您还有--题未作答，确认要交卷吗?');
    const visible = ref(false);
    const confirmLoading = ref(false);

    const showModal = () => {
      visible.value = true;
    };

    // 获取父组件传过来的ID
    const routers = useRoute();
    const id = JSON.parse(routers.query.id);
    const spinning = ref(false);
    const flag = ref(false);
    let paperData = ref({
      leftSeconds: 99999,
      radioList: [],
      multiList: [],
      judgeList: []
    });
    // 当前题目内容
    let quData = ref({
      answerList: []
    });
    //试卷信息
    // 当前答题卡
    let cardItem = ref({});
    let allItem = ref([]);
    // 试卷ID
    let paperId = ref('');
    // 单选选定值
    let radioValue = ref('');
    // 多选选定值
    let multiValue = ref([]);

    let showPrevious = ref(false);
    let showNext = ref(true);
    let handleText = ref('交卷');
    let pageLoading = ref(false);

    //上一题
    const handPrevious = function () {
      const index = cardItem.value.sort - 1
      handSave(allItem.value[index])
    }
    //下一题
    const handNext = function () {
      const index = cardItem.value.sort + 1
      handSave(allItem.value[index])
    }
    // 计时
    const doHandler = function () {
      handleText.value = '正在交卷，请等待...'
      const params = {id: paperId.value}
      console.log("交卷ID--",paperId.value)
      visible.value = false;
      confirmLoading.value = false;
      handExam(params).then(() => {
       message.success("试卷提交成功，即将进入试卷详情！")
        router.push({
          path:'/exam/result',
          query:{
            id:JSON.stringify(paperId.value)
          }
        })
      })
    }
    // 交卷
    const handHandExam = function () {
      // 交卷保存答案
      handSave(cardItem.value, function() {
        const notAnswered = countNotAnswered()
        let msg = '确认要交卷吗？'
        if (notAnswered > 0) {
          msg = '您还有' + notAnswered + '题未作答，确认要交卷吗?'
          modalText.value = msg
          visible.value = true;
        }
        doHandler()
      })
    }
    // 交卷操作
    const handleOk = () => {

      // confirmLoading.value = true;
      // setTimeout(() => {
      //   visible.value = false;
      //   confirmLoading.value = false;
      // }, 2000);
      doHandler()
    };
    /**
     * 统计有多少题没答的
     * @returns {number}
     */
    const countNotAnswered = function() {
      let notAnswered = 0

      paperData.value.radioList.forEach(function(item) {
        if (!item.answered) {
          notAnswered += 1
        }
      })

      paperData.value.multiList.forEach(function(item) {
        if (!item.answered) {
          notAnswered += 1
        }
      })

      paperData.value.judgeList.forEach(function(item) {
        if (!item.answered) {
          notAnswered += 1
        }
      })

      return notAnswered
    }
    // 保存答案
    const handSave = function (item, callback) {
      console.log("保存答案---",item.answered,"--------*+", item.quId)
      if (item.id === allItem.value[0].id) {
        showPrevious.value = false
      } else {
        showPrevious.value = true
      }

      // 最后一个索引
      const last = allItem.value.length - 1

      if (item.id === allItem.value[last].id) {
        showNext.value = false
      } else {
        showNext.value = true
      }

      const answers = multiValue.value
      if (radioValue.value !== '') {
        answers.push(radioValue.value)
      }

      const params = { paperId: paperId.value, quId: cardItem.value.quId, answers: answers, answer: '' }
      fillAnswer(params).then(() => {
        // 必须选择一个值
        if (answers.length > 0) {
          // 加入已答列表
          cardItem.value.answered = true
        }
        // 最后一个动作，交卷
        if (callback) {
          callback()
        }
        // 查找详情
        fetchQuData(item)
      })
    }
    // 单选样式
    const radioStyle = reactive({
      display: 'flex',
      height: '30px',
      lineHeight: '30px',
    });
    // 答题卡样式
    const cardItemClass = function (answered, quId) {
      console.log("cardItemClass answered, quId+++",answered +"--",quId)
      if (quId === cardItem.value.quId) {
        return 'warning'
      }

      if (answered) {
        return 'success'
      }

      if (!answered) {
        return 'default'
      }
    }
    // 试卷详情
    const fetchData = function (answered, quId) {
      if (typeof id !== 'undefined') {
        console.log("id++++++++++++++++++", id)
        paperId.value = id
        paperDetail({"id": id}).then((response) => {
          if (response.success) {
            paperData.value = response.data
            if (paperData.value.radioList) {
              cardItem.value = paperData.value.radioList[0]
            } else if (paperData.value.multiList) {
              cardItem.value = paperData.value.multiList[0]
            } else if (paperData.value.judgeList) {
              cardItem.value = paperData.value.judgeList[0]
            }
            paperData.value.radioList.forEach(function (item) {
              allItem.value.push(item)
            })
            paperData.value.multiList.forEach(function (item) {
              allItem.value.push(item)
            })

            paperData.value.judgeList.forEach(function (item) {
              allItem.value.push(item)
            })
            // 当前选定
            fetchQuData(cardItem.value)
          }
        })
      }
    }
    // 试卷详情
    const fetchQuData = function (item) {
      // 获得详情
      cardItem.value = item
      // 查找下个详情
      const params = {paperId: paperId.value, quId: item.quId}
      quDetail(params).then(response => {
        console.log("填充答案的response--",response)
        quData.value = response.data
        radioValue.value = ''
        multiValue.value = []
        // 填充该题目的答案
        quData.value.answerList.forEach((item) => {
          if ((quData.value.quType === 1 || quData.value.quType === 3) && item.checked) {
            radioValue.value = item.id
          }
          if (quData.value.quType === 2 && item.checked) {
            multiValue.value.push(item.id)
          }
        })

      })
      // 当全部请求完成之后加载计时器
      flag.value = true
    }
    fetchData();
    return {
      id,
      cardItem,
      paperId,
      paperData,
      flag,
      quData,
      radioValue,
      multiValue,
      showPrevious,
      showNext,
      handleText,
      spinning,
      pageLoading,
      modalText,
      visible,
      confirmLoading,
      showModal,
      handleOk,

      cardItemClass, // 答题卡样式
      fetchQuData, // 试卷详情
      radioStyle, // 单选样式
      handPrevious, // 上一题
      handNext, // 下一题
      doHandler, // 计时结束
      handHandExam, // 交卷
      handSave, // 下一题
    }
  }
}
</script>

<style scoped>
/*最外层*/
.mainClass {
  width: 100%;
  height: 100%;
  overflow: hidden;
}

/*头部*/
.topClass {
  width: 98%;
  height: 9%;
  margin: 1%;
  background-color: white;
  border-radius: 5px; /**设置为圆角**/
}

/*左侧*/
.leftClass {
  float: left;
  width: 25%;
  height: auto;
  margin: 1%;
  background-color: white;
  border-radius: 5px; /**设置为圆角**/
}

/*答题卡文字*/
.answerSheetText {
  width: 98%;
  margin-top: 1.5%;
  margin-bottom: 1.5%;
  background-color: #dcdfe6;
  text-align: center;
}

/*已做答未作答*/
.answer1 {
  background-color: #F4F4FF;
  border-radius: 3px; /**设置为圆角**/
  margin-left: 3%;
  color: #909399;
}

.answer2 {
  background-color: #E7FAF0;
  border-radius: 3px; /**设置为圆角**/
  margin-left: 5%;
  color: #13CE66;
}

/*右侧*/
.reightClass {
  float: right;
  width: 70%;
  height: auto;
  margin: 1%;
  background-color: white;
  border-radius: 5px; /**设置为圆角**/
}


</style>
